#include"io430.h"
#include"intrinsics.h"
#include"include.h"
#include"adc.h"
#include"data_param.h"

#define SIZE_BUFFER 10
short adcBuffer[SIZE_BUFFER];

extern volatile packet  tx_Buffer;
extern volatile packet  rx_Buffer;

extern short level_battery;

extern volatile unsigned char flag_run;  
extern volatile unsigned char flag_stop; 

extern unsigned short count_packet;

extern unsigned char from_adress;  

unsigned char flag_battery=0;



//unsigned char flag_stop; 

void Mic_Enable(void)
{
   P1OUT|= BIT1;
};

void Mic_Disable(void)
{
   P1OUT&= ~BIT1;
};

void On_ADC_battery(void)
{
  flag_battery=1;
  
  ADC10CTL1 = INCH_5  + CONSEQ_0+ SHS_0;
  ADC10CTL0 = ADC10SHT_2 + ADC10ON + ADC10IE+SREF_1+REF2_5V+REFON+ADC10SR;

  ADC10AE0  = 1<<5;  
  ADC10CTL0 &= ~ENC;
  
  while (ADC10CTL1 & BUSY);
  ADC10CTL0 |= ENC;    
  ADC10CTL0 |=ADC10SC;

};

void Off_ADC_battery(void)
{
  ADC10SA=0;
  ADC10CTL1&=~(CONSEQ_0+CONSEQ_1+CONSEQ_2+CONSEQ_3);
  ADC10DTC1=0;
  ADC10CTL0 &=~(ENC+ADC10IE+ADC10IFG); 
};

void calcul_RMS(short *_buffer_rms)
{
long  int tmp_rms=0;
unsigned char _i=0;
   
  for (_i=0;_i<96;_i++) tmp_rms+=_buffer_rms[_i];
  
  level_battery=tmp_rms/96;
  
};

short _calcul_RMS(short *_buffer_rms)
{
long  int tmp_rms=0;
unsigned char _i=0;
   
  for (_i=0;_i<96;_i++) tmp_rms+=_buffer_rms[_i];
  
  return (short)(tmp_rms/96);
  
};


#pragma vector=ADC10_VECTOR
__interrupt void ADC10_ISR(void)
{  
  WDTCTL=WDT_ARST_1000;  
  
  if (flag_battery==1)      
  {
   
   tx_Buffer.length=7;
   tx_Buffer.adress=rx_Buffer.header[0];
   tx_Buffer.header[0]=P_ADRESS;
   tx_Buffer.header[1]=0x88;
   tx_Buffer.header[2]=rx_Buffer.header[2];
   tx_Buffer.header[3]=rx_Buffer.header[3];  
   tx_Buffer.data[0]=ADC10MEM/256;
   tx_Buffer.data[1]=ADC10MEM%256;
   RFSendPacket((packet*)&tx_Buffer,tx_Buffer.length+1);
   
  };
  __delay_cycles(50);   
}

void Init_TimerA(void)
{
  TACCR0 =32000;                           // PWM Period 277 333
  TACCTL0_bit.CCIE=1;
  TACTL = TASSEL_2 + MC_2+TAIE+ID_1;       // SMCLK, up mode to 0FFFFh div 2
  P4DIR|=1<<5;
};


#pragma vector=TIMERA0_VECTOR //to TACCR0
__interrupt void TimerA0_ISR (void)
{  
  TI_CC_SPIStrobe(TI_CCxxx0_SIDLE);
  WDTCTL=WDT_ARST_1000;
  P4OUT&=~(1<<5);
}

#pragma vector=TIMERA1_VECTOR //overflow
__interrupt void TimerA1_ISR (void)
{  
  switch(TAIV)
  {
  case 0x0A:
    TI_CC_SPIStrobe(TI_CCxxx0_SRX);
    WDTCTL=WDT_ARST_1000;
    P4OUT|=(1<<5);    
   break; 
  }
}